<template>
  <div>
    <zm-form :model="form" ref="form" label-width="150px">
    <zm-form-item label="规则有效时间" prop="ruleStartTime" :rules="{required:true,message:'请填写有效时间'}">
      <zm-date-picker
        type="datetimerange"
        :target="form"
        start-key="ruleStartTime"
        end-key="ruleEndTime"
        has-tip
      ></zm-date-picker>
    </zm-form-item>
    <zm-form-item label="可用渠道" prop="isLimitXxChannel" :rules="{required:true,message:'*为必填项'}">
      <zm-data-radio
        v-model="form.isLimitXxChannel"
        :list="CHANNEL_TYPE"
        @change="handleResetChannelId"
      />
        <!-- <zm-checkbox v-if="form.isLimitXxChannel === '2'" :list="channelList" v-model="form.xxChannelId" :option="{isAllShow:false}" /> -->
    </zm-form-item>
    <zm-form-item v-if="form.isLimitXxChannel === '2'" label="指定渠道" prop="xxChannelId" :rules="{required:true,message:'*为必填项'}">
      <zm-data-select
        class="w200"
        v-model="form.xxChannelId"
        :list="channelList"
        :multiple="true"
        :str="true"
      />
    </zm-form-item>
    <zm-form-item label="是否所有公司可用" prop="isLimitCompany" :rules="{required:true,message:'*为必填项'}">
      <zm-data-radio
        v-model="form.isLimitCompany"
        :list="COMPANY_CAN_USE"
        @change="handleCanUseChange"
      />
    </zm-form-item>
    <zm-form-item label="指定公司分组" prop="companyGroupId" v-if="+form.isLimitCompany !== 0" :rules="unableCompanyIdRule">
      <zm-data-select
        class="w200"
        v-model="form.companyGroupId"
        :list="companyGroupList"
        @change="onResetRules"
        :multiple="true"
        :str="true"
      />
    </zm-form-item>
    <!-- 折扣方案 begin -->
    <zm-form-item label="折扣方案" required>
      <zm-button
        @click="addDiscountPackage"
        type="primary"
        size="mini"
        class="fr w80"
      >
        新增
      </zm-button>
    </zm-form-item>
    <zm-form-item>
      <el-card
        class="box-card rulesBox"
        v-for="(_item, _index) in form.xxRule"
        :key="_index"
      >
        <div slot="header" class="clearfix">
          <zm-edit-input
            class="dib"
            v-model="_item.name"
            :default-msg="`规则${_index + 1}`"
          />
          <zm-button
            type="text"
            class="el-icon-delete rulesBtn"
            :disabled="form.xxRule.length === 1"
            @click="onRemoveRules(_index)"
          ></zm-button>
        </div>
        <div class="text item">
          <zm-form-item label="选择公司" :prop="`xxRule.${_index}.companyType`" :rules="{
              required: true,
              message: '请选择',
              trigger: 'blur',
            }"
>
            <zm-data-radio
            v-model="_item.companyType"
            :list="ITEM_COMPANY"
            @change="handleClearCompanyName(_item,_index)"
            />
          </zm-form-item>
          <zm-form-item
            label="公司名称"
            :prop="`xxRule.${_index}.companyId`"
            :rules="{
              required: true,
              message: '请选择公司名称',
              trigger: 'change',
            }"
          >
            <zm-data-select
              v-model="_item.companyId"
              :list="_item.selectList"
              class="w200"
              :multiple="true"
              :str="true"
              clearable
              @focus="handleSelect(_item, _index)"
              @clear="handleClearCompanyName(_item,_index)"
            >
            </zm-data-select>
          </zm-form-item>
          <zm-form-item
            class="mt10 dib"
            label="签约折扣"
            :prop="`xxRule.${_index}.advancePrice`"
            :rules="{
              required: true,
              message: '请填写折扣金额',
              trigger: 'blur',
            }"
          >
            <zm-input
              class="w180"
              type="number"
              v-model="_item.advancePrice"
              placeholder="基准金额"
            >
              <template slot="append">元</template>
            </zm-input>
            抵
          </zm-form-item>
          <zm-form-item
            :prop="`xxRule.${_index}.discountPrice`"
            class="dib"
            label-width="0px"
            :rules="{
              required: true,
              message: '请填写等值金额',
              trigger: 'blur',
            }"
          >
            <zm-input
              class="w180"
              type="number"
              v-model="_item.discountPrice"
              placeholder="等值金额"
            >
              <template slot="append">元</template>
            </zm-input>
          </zm-form-item>
        </div>
      </el-card>
    </zm-form-item>
    <!-- 折扣方案 end -->
<!--     <zm-form-item label="兑换范围" required>
      <zm-button
        @click="handleAddExchange"
        type="primary"
        size="mini"
        class="fr w80"
      >
        新增
      </zm-button>
    </zm-form-item>
    <zm-form-item>
      <zm-table-data
        :data="form.xxExchange"
        :columns="exchangeColumns"
        :fetch="loadList"
        :create-fetch="false"
        :table-params="tableParams"
        :show-page="false"
        class="mb"
      >
        <zm-table-column label="操作" width="120">
          <template slot-scope="scope">
            <zm-button type="text" @click="onEdit(scope.row, scope.$index)">
              编辑
            </zm-button>
            <zm-button type="text" @click="onDelete(scope.row, scope.$index)">
              删除
            </zm-button>
          </template>
        </zm-table-column>
      </zm-table-data>
    </zm-form-item> -->
    <zm-form-item label="兑换规则" prop="exchangeRules">
      <zm-editor
        v-model="form.exchangeRules"
        placeholder="请输入兑换规则"
      ></zm-editor>
    </zm-form-item>
    </zm-form>
    <add-exchange
      v-if="exchangeVisible"
      v-model="exchangeVisible"
      :current-data="currentData"
      @handle-after="handleAfter"
    ></add-exchange>
  </div>
</template>

<script>
import tableMixin from '@/mixins/zmTableMixin'
import ZmEditor from '@/components/QuillEditor'
import addExchange from './components/AddExchange'
import { exchangeColumns, stepFormRules } from './const'
import ZmEditInput from '@/components/ZmEditInput'
import cloudApis from '@/api/src/cloud'
import { SHOW_TEXT, IS_RECOMMEND } from '@/model/type'
export default {
  name: 'PointCard',
  components: { ZmEditor, addExchange, ZmEditInput },
  mixins: [tableMixin],
  inject: ['$product'],
  props: {
    value: {
      type: Object,
      default: () => {
        return {}
      }
    },
    outIndex: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      text: '123',
      exchangeVisible: false,
      stepFormRules,
      currentData: {},
      companyList: [],
      companyGroupList: [], // 公司分组下拉项
      companyListDisabled: [],
      channelList: [], // 渠道数据
      COMPANY_CAN_USE: [
        { value: '0', name: '所有公司可用' },
        { value: '1', name: '指定公司不可用' },
        { value: '2', name: '指定公司可用' }
      ],
      ITEM_COMPANY: [
        { value: '1', name: '指定公司' },
        { value: '2', name: '公司分组' }
      ],
      CHANNEL_TYPE: [
        { value: '1', name: '全部渠道' },
        { value: '2', name: '指定渠道' }
      ]
    }
  },
  computed: {
    exchangeColumns () {
      return exchangeColumns(this)
    },
    form: {
      get () {
        return this.$product.form
      },
      set (val) {
        this.$product.form = val
      }
    },
    unableCompanyIdRule () {
      return {
        required: +this.form.isLimitCompany !== 0,
        message: '请选择指定公司分组'
      }
    }
  },
  watch: {},
  created () {
    this.getCompanyList()
    this.getChannelList()
    this.getCompanyGroupList()
    if (this.form.xxExchange.length === 0) {
      // 新增时默认取一次接口数据
      this.loadList()
    }
  },
  methods: {
    async getChannelList () {
      this.channelList = await cloudApis.getXxChannelList()
    },
    // 清空已选的不可用公司
    handleCanUseChange (val) {
      this.form.companyGroupId = ''
      this.onResetRules()
    },
    // 获取公司下拉
    async getCompanyList () {
      this.companyList = await cloudApis.getCompanyList()
    },
    // 获取公司分组下拉
    async getCompanyGroupList () {
      this.companyGroupList = await cloudApis.getCompanyGroupList()
    },
    async loadList () {
      const _res = await cloudApis.getExchangeData({isCoupon: 1})
      this.form.xxExchange = _res.list || []
      this.form.exchangeRules = _res.exchangeRules || ''
    },

    // 新增规则
    addDiscountPackage () {
      this.form.xxRule.push({
        companyType: '1',
        companyId: '',
        companyName: '',
        benchmarkMoney: '',
        equMoney: '',
        name: ''
      })
    },
    // 删除规则
    onRemoveRules (index) {
      this.form.xxRule.splice(index, 1)
    },
    // 新增兑换范围
    handleAddExchange () {
      this.exchangeVisible = true
      this.currentData = {
        type: 'add'
      }
    },
    // 编辑兑换范围
    onEdit (row, index) {
      console.log('兑换范围单项-', row)
      this.exchangeVisible = true
      this.currentData = {
        ...row,
        type: 'edit',
        currentIndex: index
      }
    },
    // 删除兑换规则
    onDelete (row, index) {
      this.$confirm(
        '是否确认删除该兑换规则，删除后不可恢复，请谨慎操作',
        '操作提示',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.form.xxExchange.splice(index, 1)
        })
        .catch((e) => {
          console.log(e)
        })
    },
    // 兑换范围弹窗回调
    handleAfter (type, data, currentIndex) {
      if (type === 'edit') {
        this.form.xxExchange[currentIndex] = data
      }
      if (type === 'add') {
        this.form.xxExchange.push(data)
      }
    },
    // 获取可选的公司分组数组
    getFilterCompanyGroupList (item, index) {
      let res = []
      const selectedIds = this.form.companyGroupId.split(',')
      if (this.form.isLimitCompany === '2') { // 指定公司可用
        res = this.companyGroupList.filter(item => {
          return selectedIds.includes(item.value)
        })
      } else if (this.form.isLimitCompany === '1') { // 指定公司不可用
        res = this.companyGroupList.filter(item => {
          return selectedIds.includes(item.value) === false
        })
      } else { // 所有公司可用
        res = this.companyGroupList
      }
      // 过滤掉除自身外已选的公司分组
      const otherXxRule = this.form.xxRule.filter((item, idx) => idx !== index)
      const selectedGroupIds = otherXxRule.map(item => item.companyId.toString().split(',')).flat(Infinity)
      if (selectedGroupIds && selectedGroupIds.length > 0) {
        res = res.filter(item => {
          return selectedGroupIds.includes(item.value) === false
        })
      }
      return res
    },
    // 返回当前规则可选的公司名称下拉数据
    async handleSelect (item, index) {
      // 获取当前可选的下拉数据
      let itemCompanyList // 当前规则的下拉选项
      if (item.companyType === '1') { // 指定公司
        const _Params = {
          type: this.form.isLimitCompany,
          groupId: this.form.companyGroupId
        }
        // 指定公司获取公司数据并过滤掉其他规则已选的公司
        itemCompanyList = await cloudApis.getCompanyList(_Params)
        // 过滤掉其他规则已选的公司
        const otherXxRule = this.form.xxRule.filter((item, idx) => idx !== index)
        const selectedGroupIds = otherXxRule.map(item => item.companyId.toString().split(',')).flat(Infinity)
        if (selectedGroupIds && selectedGroupIds.length > 0) {
          itemCompanyList = itemCompanyList.filter(item => {
            return selectedGroupIds.includes(item.value) === false
          })
        }
      } else if (item.companyType === '2') {
        // 公司分组则对指定的公司分组 和 其他规则已选的公司分组 进行过滤
        itemCompanyList = this.getFilterCompanyGroupList(item, index)
      }

      // // 获取公司名称
      if (item.companyId && item.companyId.length > 0) {
        const _companyIdList = item.companyId.toString().split(',')
        const selectedArr = itemCompanyList.filter(i => _companyIdList.includes(i.value))
        item.companyName = selectedArr.map(i => i.name).join(',')
      }
      if (item.companyId instanceof Array) {
        item.companyId = item.companyId.join(',')
      }
      this.$set(this.form.xxRule, index, {
        ...item,
        selectList: itemCompanyList
      })
      // console.log(item, index, this.form.xxRule[index], 'xxRule')
    },
    handleClearCompanyName (item, index) {
      this.$set(this.form.xxRule, index, {
        ...item,
        companyId: '',
        companyName: ''
      })
    },
    // 指定公司不可用
    handleCanUseFilterList () {
      this.companyListDisabled = this.form.xxRule
        .map((item) => {
          return item.companyId.toString().split(',')
        })
        .flat()
        .filter(Boolean)
    },
    validate () {
      return this.$refs.form.validate()
    },
    // 指定公司数据变动则清空折扣方案所有规则的公司名称
    onResetRules () {
      const _list = this.form.xxRule.map(item => {
        return {
          ...item,
          companyId: '',
          companyName: '',
          companyGroupId: '',
          companyGroupName: ''
        }
      })
      this.$set(this.form, 'xxRule', _list)
    },
    // 清除 channelId 字段
    handleResetChannelId () {
      this.$set(this.form, 'channelId', '')
    }
  }
}
</script>

<style scoped lang='scss'>
.rulesBox {
  margin-bottom: 10px;
  .rulesBtn {
    float: right;
    padding: 3px 0;
    margin-right: 15px;
  }
}
.mb {
  margin-bottom: 15px;
}
</style>
